package service
import (
	"errors"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"gin-luban-server/model/request"
)
//@author: heyibo
//@function: CreateDatabaseUser
//@description: 创建一个数据库信息
//@param: database CMDBDatabase
//@return: err error, database model.CMDBDatabaseUser

func CreateDatabaseUser(databaseUser model.CMDBDatabaseUser) (err error) {
	err = global.GVA_DB.Create(&databaseUser).Error
	return err
}

//@author: heyibo
//@function: DeleteDatabaseUser
//@description: 删除数据库信息
//@param: id ,database CMDBDatabaseUser
//@return: err error

func DeleteDatabaseUser(id float64) (err error) {
	// 1. 判断不存在没有在其他 表中使用 虚拟机中 <- 待补充
	var databaseUser model.CMDBDatabaseUser
	// 2. 删除
	err = global.GVA_DB.Where("id = ?", id).Delete(&databaseUser).Error
	return err
}

//@author: heyibo
//@function: UpdateDatabaseUser
//@description: 更改一个角色
//@param: database model.CMDBDatabaseUser
//@return:err error, database model.CMDBDatabaseUser
func UpdateDatabaseUser(databaseUser model.CMDBDatabaseUser) (err error) {
	var total int64
	var data []model.CMDBDatabaseUser
	err = global.GVA_DB.Where("database_name = ? AND id != ?",databaseUser.DatabaseName,databaseUser.ID).Find(&data).Count(&total).Error
	if total >= 1 {
		return errors.New("数据库名称已存在！")
	}
	// 通过唯一ID进行更新
	err = global.GVA_DB.Where("id = ?", databaseUser.ID).First(&model.CMDBDatabaseUser{}).Updates(&databaseUser).Error
	return err
}

//@author: heyibo
//@function: FindDatabasetById
//@description: 根据Id查询数据
//@param: id int
//@return: err error, database model.CMDBDatabase
func FindDatabaseUserById(id float64) (err error, databaseUser model.CMDBDatabaseUser) {
	err = global.GVA_DB.Where("id = ?", id).First(&databaseUser).Error
	return err, databaseUser
}

//@author: heyibo
//@function: GetDatabaseUserInfoList
//@description: 分页获取数据
//@param: info request.PageInfo
//@return: err error, list interface{}, total int64
func GetDatabaseUserInfoList(info request.SearchDatabaseUserParams) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&model.CMDBDatabaseUser{})
	var databaseList []model.CMDBDatabaseUser
	if info.ProjectCode != "" {
		db = db.Where("project_code = ?", info.ProjectCode)
	}
	if info.ClusterName != "" {
		db = db.Where("cluster_name = ?", info.ClusterName)
	}

	if info.UserName != "" {
		db = db.Where("user_name = ?",info.UserName)
	}
	if info.Status != nil {
		db = db.Where("`status` = ?", info.Status)
	}
	err = db.Count(&total).Error

	if err != nil {
		return err, databaseList, total
	} else {
		db = db.Limit(limit).Offset(offset)
		err = db.Preload("Database").Preload("Project").Find(&databaseList).Error
	}
	return err, databaseList, total
}
